﻿@using Telerik.Web.Mvc.UI;
@model ProductModel
@{
    Layout = "";
}

@if (Model.Id > 0)
{
    /*hide "add spec" table if no attributes are defined*/
    if (Model.AddSpecificationAttributeModel.AvailableAttributes.Count > 0)
    {
        <script type="text/javascript">
            $(function() {
                $("#@Html.FieldIdFor(model => model.AddSpecificationAttributeModel.SpecificationAttributeId)").on('change', function() {

                    var selectedItem = $(this).val();
                    var ddlSpecOptions = $("#@Html.FieldIdFor(model => model.AddSpecificationAttributeModel.SpecificationAttributeOptionId)")
                    $.ajax({
                        cache: false,
                        type: "GET",
                        url: "@(Url.Action("GetOptionsByAttributeId", "SpecificationAttribute"))",
                        data: { "attributeId": selectedItem },
                        success: function (data) {
                            ddlSpecOptions.html('');
                            $.each(data, function(id, option) {
                                ddlSpecOptions.append($('<option></option>').val(option.id).html(option.name));
                            });
                            ddlSpecOptions.trigger("change");
                        },
                        error: function (xhr, ajaxOptions, thrownError) {
                            alert('Failed to retrieve specification options.')
                        }
                    });
                });
            });

            $(document).ready(function () {
                $('#addProductSpec').click(function () {
                    var specificationAttributeOptionId = $("#@Html.FieldIdFor(model => model.AddSpecificationAttributeModel.SpecificationAttributeOptionId)").val();
                    var allowFiltering = $("#@Html.FieldIdFor(model => model.AddSpecificationAttributeModel.AllowFiltering)").val();
                    var showOnProductPage = $("#@Html.FieldIdFor(model => model.AddSpecificationAttributeModel.ShowOnProductPage)").val();
                    var displayOrder = $("#@Html.FieldIdFor(model => model.AddSpecificationAttributeModel.DisplayOrder)").val();

                	$('#addProductSpec').attr('disabled', true);

                    $.ajax({
                        cache: false,
                        type: "POST",
                        url: "@(Url.Action("ProductSpecificationAttributeAdd", "Product"))",
                        data: { "specificationAttributeOptionId": specificationAttributeOptionId, "allowFiltering": allowFiltering, "showOnProductPage": showOnProductPage, "displayOrder": displayOrder, "productId": @Model.Id },
                    	success: function (data) {
                    		$('#addProductSpec').attr('disabled', false);
                    		if (data.success) {
                    			$("#specificationattributes-grid").data('tGrid').ajaxRequest();
                    		}
                    		else {
                    			displayNotification(data.message, 'warning');
                    		}
                        },
                        error: function (xhr, ajaxOptions, thrownError) {
                            alert('Failed to add specification attribute.')
                            $('#addProductSpec').attr('disabled', false);
                        }
                    });
                });
            });
        </script>

        <table class="adminContent mb-5">
			<tr>
				<td colspan="2">
					<div class="admin-config-group">
						<div class="head">@T("Admin.Catalog.Products.SpecificationAttributes.AddNew")</div>
					</div>
				</td>
			</tr>
            <tr>
                <td class="adminTitle">
                    @Html.SmartLabelFor(model => model.AddSpecificationAttributeModel.SpecificationAttributeId)
                </td>
                <td class="adminData">
                    @Html.DropDownListFor(model => model.AddSpecificationAttributeModel.SpecificationAttributeId, Model.AddSpecificationAttributeModel.AvailableAttributes)
                    @Html.ValidationMessageFor(model => model.AddSpecificationAttributeModel.SpecificationAttributeId)
                </td>
            </tr>
            <tr>
                <td class="adminTitle">
                    @Html.SmartLabelFor(model => model.AddSpecificationAttributeModel.SpecificationAttributeOptionId)
                </td>
                <td class="adminData">
                    @Html.DropDownListFor(model => model.AddSpecificationAttributeModel.SpecificationAttributeOptionId, Model.AddSpecificationAttributeModel.AvailableOptions)
                    @Html.ValidationMessageFor(model => model.AddSpecificationAttributeModel.SpecificationAttributeOptionId)
                </td>
            </tr>
            <tr>
                <td class="adminTitle">
                    @Html.SmartLabelFor(model => model.AddSpecificationAttributeModel.AllowFiltering)
                </td>
                <td class="adminData">
                    @Html.EditorFor(model => model.AddSpecificationAttributeModel.AllowFiltering)
                    @Html.ValidationMessageFor(model => model.AddSpecificationAttributeModel.AllowFiltering)
                </td>
            </tr>
            <tr>
                <td class="adminTitle">
                    @Html.SmartLabelFor(model => model.AddSpecificationAttributeModel.ShowOnProductPage)
                </td>
                <td class="adminData">
                    @Html.EditorFor(model => model.AddSpecificationAttributeModel.ShowOnProductPage)
                    @Html.ValidationMessageFor(model => model.AddSpecificationAttributeModel.ShowOnProductPage)
                </td>
            </tr>
            <tr>
                <td class="adminTitle">
                    @Html.SmartLabelFor(model => model.AddSpecificationAttributeModel.DisplayOrder)
                </td>
                <td class="adminData">
                    @Html.EditorFor(model => model.AddSpecificationAttributeModel.DisplayOrder)
                    @Html.ValidationMessageFor(model => model.AddSpecificationAttributeModel.DisplayOrder)
                </td>
            </tr>
            <tr>
				<td class="adminTitle">
					&nbsp;
				</td>
				<td class="adminData">
					<button type="button" name="addProductSpec" id="addProductSpec" class="btn btn-primary">
						<i class="fa fa-plus"></i>
						<span>@T("Admin.Catalog.Products.SpecificationAttributes.AddButton")</span>
					</button>
				</td>
            </tr>
        </table>
    
        <div>
            <script type="text/javascript">
                function OnCommand(e) {
                    var link = $(e.row).find(".spec-attr-opt");
                    if(e.name == "edit") {
                        initXEditable(link);
                    }
                }

                function OnGridEdit(e) {
                    link = $(e.currentTarget).find(".t-grid-edit-row .spec-attr-opt");
                    initXEditable(link);
                }

                function OnGridRowDataBound(e) {
                    var link = $(e.row).find(".spec-attr-opt");
                    initXEditable(link);
                }

                function initXEditable(link) {
                	if (!$.fn.editable)
                		return;

					var optionsUrl = link.data('options-url'),
						initText = link.text(),
						selectedId = link.data('value');

                    link.editable({
                        tpl: '<select class="skin select-editable drop-editable"></select>',
						type: 'select2',
						url: '@Url.Action("SetAttributeValue", "SpecificationAttribute")',
						unsavedclass: null,
                        inputclass: 'form-control form-control-sm',
						mode: 'popup',
						placement: 'right',
						autotext: 'auto',
						select2: {
							lazy: {
								url: optionsUrl
							},
							init: {
								id: selectedId,
								text: initText
							}
						},
						display: function (value, sourceData) {
							// ABS4: display new value, otherwise always 'empty' is displayed.
							if (sourceData && sourceData.success) {
								$(this).html(sourceData.name);
							}
						},
						success: function (response, newValue) {
							if (response.success) {
								// we have to overwrite grid data so the correct values are displayed when a value was saved with x-editable
								// else the data that initialy populated the client template would be displayed
								var grid = $('#specificationattributes-grid').data('tGrid');

								// get the index of the tr holding the updated value because the data is stored in an array
								var index = link.closest("tr").index();
								var data = grid.data[index];

								// overwrite data of option id and name
								data.SpecificationAttributeOptionId = newValue;
								data.SpecificationAttributeOptionName = response.name;
							}
							else {
								displayNotification(response.message, 'warning');
								$("#specificationattributes-grid").data('tGrid').ajaxRequest();
							}
						}
					});

				}
            </script>

            @(Html.Telerik().Grid<ProductSpecificationAttributeModel>()
				.Name("specificationattributes-grid")
				.DataKeys(x =>
				{
					x.Add(y => y.Id).RouteKey("psaId");
				})
				.Columns(columns =>
				{
					columns.Bound(x => x.SpecificationAttributeName)
						.Width(200)
						.ReadOnly();
					columns.Bound(x => x.SpecificationAttributeOptionName)
						.ClientTemplate("<a href='#' data-options-url='<#= SpecificationAttributeOptionsUrl #>' data-pk='<#= SpecificationAttributeId #>' data-value='<#= SpecificationAttributeOptionId #>' id='<#= Id #>' class='editable editable-click spec-attr-opt'><#= SpecificationAttributeOptionName #></a>")
						.ReadOnly()
						.Width(300);
					columns.Bound(x => x.AllowFiltering)
						.Width(100)
						.ClientTemplate(@Html.SymbolForBool("AllowFiltering"))
						.Centered();
					columns.Bound(x => x.ShowOnProductPage)
						.Width(100)
						.ClientTemplate(@Html.SymbolForBool("ShowOnProductPage"))
						.Centered();
					columns.Bound(x => x.DisplayOrder)
						.Centered()
						.Width(100);
					columns.Command(commands =>
					{
						commands.Edit().Localize(T);
						commands.Delete().Localize(T);
					}).Width(180).HtmlAttributes(new { align = "right" });
				})
				.ClientEvents(e =>
				{
					e.OnEdit("OnGridEdit");
					e.OnRowDataBound("OnGridRowDataBound");
				})
				.Editable(x =>
				{
					x.Mode(GridEditMode.InLine);
				})
				.DataBinding(dataBinding =>
				{
					dataBinding.Ajax().Select("ProductSpecAttrList", "Product", new { productId = Model.Id })
						.Update("ProductSpecAttrUpdate", "Product")
						.Delete("ProductSpecAttrDelete", "Product");
				})
				.EnableCustomBinding(true))
        </div>
    }
    else
    {
        <div class="alert alert-danger">
            @T("Admin.Catalog.Products.SpecificationAttributes.NoAttributes")
        </div>
    }
}
else
{
    <div class="alert alert-danger">
        @T("Admin.Catalog.Products.SpecificationAttributes.SaveBeforeEdit")
    </div>
}
